package com.changgou.pay.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.pay.config.RabbitMQConfig;
import com.changgou.pay.service.WXPayService;
import com.changgou.util.ConvertUtils;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: HuangFu
 * @Date: 2020/2/19 11:00
 * @Description: 微信支付
 */
@RestController
@RequestMapping("/wxpay")
public class WXPayController {

    @Autowired
    private WXPayService wxPayService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 微信下单
     * @param orderId
     * @param money
     * @return
     */
    @GetMapping("/nativePay")
    public Result<Map> nativePay(@RequestParam("orderId") String orderId,@RequestParam("money") Integer money){
        Map map = wxPayService.nativePay(orderId, money);
        return new Result(true, StatusCode.OK,"下单成功",map);
    }

    @RequestMapping("/notify")
    public void notifyLogic(HttpServletRequest request, HttpServletResponse response){
        System.out.println("支付成功回调");

        try {
            //获取微信回执数据
            String wxXml = ConvertUtils.convertToString(request.getInputStream());
            System.out.println("wxXml:"+wxXml);
            Map<String, String> map = WXPayUtil.xmlToMap(wxXml);

            if("SUCCESS".equals(map.get("result_code"))){

                Map orderMap = wxPayService.orderQuery(map.get("out_trade_no"));
                if("SUCCESS".equals(orderMap.get("result_code"))){
                    Map<String, String> mqMap = new HashMap<>(16);

                    mqMap.put("transactionId", (String) orderMap.get("transaction_id"));
                    mqMap.put("orderId", (String) orderMap.get("out_trade_no"));

                    //发送订单服务消息
                    rabbitTemplate.convertAndSend("", RabbitMQConfig.ORDER_PAY, JSON.toJSONString(mqMap));

                    //发送支付通知，完成双向通信
                    rabbitTemplate.convertAndSend("paynotify","",orderMap.get("out_trade_no"));
                }
            }else {
                //输出错误原因
                System.out.println(map.get("err_code_des"));
            }

            //给微信一个结果通知
            response.setContentType("text/xml");
            String data="<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 查询微信订单信息
     * @param orderId
     * @return
     */
    @GetMapping("/query/{orderId}")
    public Result<Map> queryOrder(@PathVariable("orderId") String orderId){
        Map map = wxPayService.orderQuery(orderId);
        return new Result(true,StatusCode.OK,"",map);
    }

    /**
     * 关闭订单
     * @param orderId
     * @return
     */
    @PostMapping("/close/{orderId}")
    public Result<Map> closeOrder(@PathVariable("orderId") String orderId){
        Map map = wxPayService.closeOrder(orderId);
        return new Result(true,StatusCode.OK,"",map);
    }

}
